/**
 * 
 * @Project le cOeur - Data Virtualization
 * @Date 08.12.2012
 * @Author Aebi Pascal, Kocher Marc
 * @School BFH-TI Biel, Bachelor Thesis
 *
 */

package main.implementation.representation;

import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import main.framework.http.ContentType;
import main.framework.http.MessageBody;
import main.framework.representation.RepresentationCreator;
import main.framework.resource.Resource;
import main.framework.resource.ResourceData;

/**
 * This class represents a representation creator for the JSON content type.
 */
public class JSONRepresentationCreator extends RepresentationCreator {

	/**
	 * Creates a representation creator for the JSON content type.
	 * 
	 * @param contentType The desired content type for the representations to be created by the representation creator.
	 */
	public JSONRepresentationCreator(ContentType contentType) {
		super(contentType);
	}

	@Override
	public MessageBody createRepresentation(String data) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("json", data);
		String representationString = jsonObject.toJSONString();
		return new MessageBody(representationString, super.contentType);
	}

	@Override
	public MessageBody createRepresentation(ResourceData resourceData) {
		String uriNode = resourceData.getResource().getURINode().getUriNode();
        List<Resource> childrenResources = resourceData.getResource().getChildren();
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		for (int i = 0; i < resourceData.getData().size(); i++) {
			for (int j = 0; j < resourceData.getData().get(i).length; j++){
				if(childrenResources.size() == 0){
					// last node --> data comes from SQL query, first row are the column names
					if (i > 0){
						JSONObject data = new JSONObject();
						data.put(resourceData.getData().get(0)[j], resourceData.getData().get(i)[j]);
						jsonArray.add(data);
					}
				} else {
					jsonArray.add(childrenResources.get(i).getURINode().getUriNode());
				}
			}
		}
		jsonObject.put(uriNode, jsonArray);
		String representationString = jsonObject.toJSONString();
        MessageBody messageBody = new MessageBody(representationString, super.contentType);
		return messageBody;
	}

}
